package com.utcook.host.fragmentdialog

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.Observable
import androidx.fragment.app.Fragment
import com.utcook.host.fragmentdialog.databinding.FragmentManualCookingBinding

class ManualCookingFragment : Fragment() {

    private var _binding: FragmentManualCookingBinding? = null
    private val binding get() = _binding!!
    private var burnerViewModel: BurnerViewModel? = null
    private var burnerIndex: Int = 0
    private var stateListener: Observable.OnPropertyChangedCallback? = null

    companion object {
        fun newInstance(burnerIndex: Int, viewModel: BurnerViewModel): ManualCookingFragment {
            val fragment = ManualCookingFragment()
            fragment.burnerIndex = burnerIndex
            fragment.burnerViewModel = viewModel
            return fragment
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentManualCookingBinding.inflate(inflater, container, false)
        
        setupManualCooking()
        setupViewModelListener()
        
        return binding.root
    }

    private fun setupManualCooking() {
        burnerViewModel?.let { viewModel ->
            binding.viewModel = viewModel
            binding.burnerIndex = burnerIndex
            binding.executePendingBindings()
            
            setupTemperatureSeekBar()
        }
    }

    private fun setupViewModelListener() {
        stateListener = object : Observable.OnPropertyChangedCallback() {
            override fun onPropertyChanged(sender: Observable?, propertyId: Int) {
                updateManualCookingState()
            }
        }
        burnerViewModel?.selectedBurnerIndex?.addOnPropertyChangedCallback(stateListener!!)
    }

    private fun setupTemperatureSeekBar() {
        binding.temperatureSeekbar.setOnSeekBarChangeListener(object : android.widget.SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: android.widget.SeekBar?, progress: Int, fromUser: Boolean) {
                if (fromUser) {
                    burnerViewModel?.setTemperature(progress)
                }
            }
            override fun onStartTrackingTouch(seekBar: android.widget.SeekBar?) {}
            override fun onStopTrackingTouch(seekBar: android.widget.SeekBar?) {}
        })
    }

    private fun updateManualCookingState() {
        if (_binding == null) return
        
        burnerViewModel?.let { viewModel ->
            binding.burnerIndex = burnerIndex
            binding.executePendingBindings()
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        stateListener = null
        _binding = null
    }
} 